import 'package:bxultimate/app/router/router_name.dart';
import 'package:bxultimate/data/request/organization_request.dart';
import 'package:bxultimate/domain/application/organization/AttendanceClockingCreateDto.dart';
import 'package:bxultimate/domain/application/organization/AttendanceTypeDto.dart';
import 'package:bxultimate/domain/common/MapLatLonDto.dart';
import 'package:bxultimate/domain/common/result.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:tdesign_flutter/src/components/cell/td_cell.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

import 'state.dart';

class OrganizationAttendanceCreateController extends GetxController {
  final OrganizationAttendanceCreateState state =
      OrganizationAttendanceCreateState();

  MapLatLonDto mapLatLonDto = MapLatLonDto();
  TextEditingController titleController = TextEditingController();
  TextEditingController distanceController = TextEditingController();
  TextEditingController remarkController = TextEditingController();

  TextEditingController customTitleController = TextEditingController();

  void showUpTimeSelect(type) {
    var now = DateTime.now();
    TDPicker.showDatePicker(Get.context, title: '选择时间', onConfirm: (selected) {
      if (type == 1) {
        state.createDto = state.createDto.copyWith(
            taskStartTime: '${selected['year'].toString().padLeft(4, '0')}-'
                '${selected['month'].toString().padLeft(2, '0')}-'
                '${selected['day'].toString().padLeft(2, '0')} ');
      } else {
        state.createDto = state.createDto.copyWith(
            taskEndTime: '${selected['year'].toString().padLeft(4, '0')}-'
                '${selected['month'].toString().padLeft(2, '0')}-'
                '${selected['day'].toString().padLeft(2, '0')} ');
      }
      Get.back();
    }, initialDate: [
      now.year,
      now.month,
      now.day,
    ],dateEnd: [2055, 12, 31]);
  }

  void showCustomTimeSelect(type) {
    var now = DateTime.now();
    TDPicker.showDatePicker(Get.context, title: '选择时间', onConfirm: (selected) {
      if (type == 1) {
        state.customStartTime =
            '${selected['hour'].toString().padLeft(2, '0')}:'
            '${selected['minute'].toString().padLeft(2, '0')}:'
            '${selected['second'].toString().padLeft(2, '0')}';
      } else {
        state.customEndTime = '${selected['hour'].toString().padLeft(2, '0')}:'
            '${selected['minute'].toString().padLeft(2, '0')}:'
            '${selected['second'].toString().padLeft(2, '0')}';
      }
      Get.back();
    },
      useYear: false,
      useMonth: false,
      useDay: false,
      useHour: true,
      useMinute: true,
      useSecond: true,
      initialDate: [
      now.hour,
      now.minute,
      now.second,
    ], dateEnd: [2055, 12, 31],);
  }

  // 地址选择
  Future<void> addressSelect(TDCell cell) async {
    mapLatLonDto = await Get.toNamed(RouterName.commonMapPointSelect);
    state.addressName = mapLatLonDto.address;
    // 设置经纬度
    state.createDto =state.createDto.copyWith(
      lat: mapLatLonDto.lat,
      lon: mapLatLonDto.lon,
      address: mapLatLonDto.address,
    );

  }

  // 打卡方式选择
  void attendanceTypeSelect(TDCell cell) async {
    List<AttendanceTypeDto> list =
        await OrganizationRequest.getAttendanceType();
    List<String> selectList = list.map((e) => e.dictLabel!).toList();
    TDPicker.showMultiPicker(Get.context, title: '选择打卡方式',
        onConfirm: (selected) {
      state.clockingType = list[selected[0]].dictLabel;
      var clockType = list[selected[0]].dictValue;
      state.createDto =
          state.createDto.copyWith(clockType: int.parse(clockType!));
      Get.back();
    }, data: [selectList]);
  }

  void toSelectUser(TDCell cell) async {
    state.idcardList = await Get.toNamed(RouterName.organizationSelectUser,
        arguments: Get.arguments);
  }

  void addCustom() {
    var list = state.createDto.attendanceClockingTimeList;
    if (list == null) {
      list = [];
    }
    list.add(AttendanceClockingTimeList(
        startTime: state.customStartTime,
        endTime: state.customEndTime,
        label: customTitleController.text));
    state.createDto =
        state.createDto.copyWith(attendanceClockingTimeList: list);

    print(list.toString());
    // 清空三个变量
    customTitleController.text = '';
    state.customStartTime = '';
    state.customEndTime = '';

    Get.back();
  }


  void removeClockingTimeList(int i) {
    var list = state.createDto.attendanceClockingTimeList;
    list!.removeAt(i);
    state.createDto =
        state.createDto.copyWith(attendanceClockingTimeList: list);
  }

  // 发布
  void publish() async {
    if (titleController.text == '') {
      SmartDialog.showNotify(msg: '请输入标题', notifyType: NotifyType.failure);
      return;
    }

    if (state.createDto.taskStartTime == null ||
        state.createDto.taskEndTime == null) {
      SmartDialog.showNotify(msg: '请选择时间', notifyType: NotifyType.failure);
      return;
    }

    if (state.createDto.lat == null || state.createDto.lon == null) {
      SmartDialog.showNotify(msg: '请选择打卡地址', notifyType: NotifyType.failure);
      return;
    }

    if (distanceController.text == '') {
      SmartDialog.showNotify(msg: '请输入打卡范围', notifyType: NotifyType.failure);
      return;
    }

    if (state.idcardList.length == 0) {
      SmartDialog.showNotify(msg: '请选择打卡人员', notifyType: NotifyType.failure);
      return;
    }

    if (state.createDto.clockType == null) {
      SmartDialog.showNotify(msg: '请选择打卡方式', notifyType: NotifyType.failure);
      return;
    }
    if (
        state.createDto.attendanceClockingTimeList == null
    || state.createDto.attendanceClockingTimeList!.length == 0) {
      SmartDialog.showNotify(msg: '请添加考勤规则', notifyType: NotifyType.failure);
      return;
    }

    state.createDto = state.createDto.copyWith(
        title: titleController.text,
        distance: distanceController.text,
        remark: remarkController.text,
        teamId: Get.arguments,
        idcardList: state.idcardList);

    await OrganizationRequest.createAttendanceClocking(state.createDto);
    SmartDialog.showNotify(msg: '发布成功', notifyType: NotifyType.success);
    Get.back();
  }
}
